import random
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.core.cache import cache
import string
from django.http import JsonResponse
from django.core.signing import Signer
from datetime import timedelta
from test_login.models import User
from .models import TestCase


# Create your views here.
def createtoken(name):
    # 产生一个8位的随机字符串
    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    # 生成token
    token = Signer().sign(randomstr + name)
    # 把token设置到缓存中
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    # 反回token
    return token


def checktoken(request):
    # 现获取header中的token
    reqtoken = request.META.get("HTTP_TOKEN")
    # 检查前端有没有传过来token
    if reqtoken is None:
        # 如果前端没有传token 返回False和自己定义的一个字符串
        return False, 'xxxx'
    # 反签名
    unsingtoken = Signer().unsign(reqtoken)
    # 取出用户名
    name = unsingtoken[8:]
    # 从缓存中获取token
    token = cache.get(f'test_{name}')
    # 判断从缓存中获取的token还存不存在
    if token is None:
        # 如果缓存中还不存在token 返回False和自己定义的一个字符串
        return False, 'xxxx'
    # 如果缓存中还存在token
    return True, name


@api_view(['post'])
def addcase(request):
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg': "未登录，用例不可添加"
        }, status=404)
    data = JSONParser().parse(request)
    casename = data.get('casename')
    priority = data.get('priority')
    review_status = data.get('review_status')
    TestCase(casename=casename, priority=priority, review_status=review_status).save()
    return JsonResponse({
        'msg': "添加成功"
    })


@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    userobj = User.objects.get(name=name)
    if userobj.password == password:
        token = createtoken(name)
        return JsonResponse({
            'code': 200,
            'msg': "登录成功",
            'token': token
        })
    return JsonResponse({
        'msg': "登录失败",
    }, status=400)
